package com.neusoft.databus.agent.interactive.collect;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.web.client.RestTemplate;

import com.neusoft.bizcore.web.utils.JsonUtils;
import com.neusoft.bizcore.web.utils.SpringUtil;
import com.neusoft.databus.agent.pool.ptrest.JhrestConnector;
import com.neusoft.databus.common.bean.CommandBean;
import com.neusoft.databus.common.bean.MetricBean;
import com.neusoft.databus.common.bean.ResourceBean;
import com.neusoft.databus.common.connection.JhportstatusConnection;
import com.neusoft.databus.common.exception.ConfigErrorException;
import com.neusoft.databus.common.interactive.collect.Collector;
import com.neusoft.databus.common.parser.Parser;

import lombok.extern.slf4j.Slf4j;

/**
 * 获取IT设备监控数据-端口状态
 *
 * @author sunchf
 * @date 2022-11-02 14:26
 */
@Slf4j
public class JhportstatusJhrestCollector extends Collector<RestTemplate> {

    private static final String RSP_CODE = "rspCode";

    public JhportstatusJhrestCollector(Parser parser) {
        super(parser);
        this.connector = SpringUtil.getBean(JhrestConnector.class);
    }

    @Override
    protected void doCollect(CommandBean command) throws Exception {

        if (command.getResourceBean().size() != 1) {
            throw new ConfigErrorException("不支持批量采集");
        }

        final List<MetricBean> metrics = command.getResourceBean().get(0).getMetrics();
        if (metrics.size() == 0) {
            throw new ConfigErrorException("端口状态采集需要配置指标");
        }

        try {
            this.conn = this.connector.getConn(command.getConnection().asUsedConnection());
            this.sendCommand(command);

        } catch (final Exception e) {
            throw e;
        } finally {
            try {
                if (JhportstatusJhrestCollector.log.isDebugEnabled()) {
                    JhportstatusJhrestCollector.log.debug("return connection object to poll, {}",
                            command.getConnection());
                }
                this.connector.returnConn(command.getConnection().asUsedConnection(), this.conn);
            } catch (final Exception e) {

            }
        }

    }

    /**
     * 参照文档《资产相关统计接口需求2022-11-02.docx》
     *
     * @param commandBean
     */
    @SuppressWarnings("unchecked")
    public void sendCommand(CommandBean commandBean) {

        final ResourceBean resource = commandBean.getResourceBean().get(0);
        if (JhportstatusJhrestCollector.log.isInfoEnabled()) {
            JhportstatusJhrestCollector.log.info("begin to communicate with jh portstatus server");
        }
        final JhportstatusConnection connection = (JhportstatusConnection) commandBean.getConnection();

        final String url = connection.getUrl();
        final Map<String, Object> config = resource.getConfig();

        // 该参数是在DataBus资源扩展配置中配置
        final String deviceId = (String) config.get("deviceId");

        // 拼接端口流量的远程地址
        final String requestUrl = url + "?deviceId=" + deviceId;
        if (JhportstatusJhrestCollector.log.isDebugEnabled()) {
            JhportstatusJhrestCollector.log.debug("获取端口状态数据，请求URL：{}", requestUrl);
        }

        final String resultStr = this.conn.getForObject(requestUrl, String.class);
        if (JhportstatusJhrestCollector.log.isDebugEnabled()) {
            JhportstatusJhrestCollector.log.debug("获取端口状态数据，返回结果：{}", resultStr);
        }

        final Map<String, Object> resultMap = JsonUtils.jsonToMap(resultStr);

        if (resultMap.containsKey(JhportstatusJhrestCollector.RSP_CODE)
                && "0".equals(resultMap.get(JhportstatusJhrestCollector.RSP_CODE))) {

            final List<Map<String, Object>> portDataList = (List<Map<String, Object>>) resultMap.get("portData");
            final List<Map<String, Object>> parsedPortDataList = portDataList.stream().map(it -> {
                final Map<String, Object> map = new HashMap<>();
                map.put("name", it.get("name"));
                map.put("deviceid", String.valueOf(it.get("id")));
                if ("UP".equalsIgnoreCase((String) it.get("ifOperStatus"))
                        && "UP".equalsIgnoreCase((String) it.get("ifAdminStatus"))) {
                    map.put("mStatus", 1);
                } else {
                    map.put("mStatus", 0);
                }
                return map;
            }).collect(Collectors.toList());

            final String jsonStr = JsonUtils.pojoToJson(parsedPortDataList);
            resource.getMetrics().forEach(m -> {
                m.setOriginalValue(jsonStr);
                m.setValue(jsonStr);
            });
        }
    }
}
